//
//  HomePageContentViewController.m
//  ShowYork
//
//  Created by hxh on 2020/9/29.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "HomePageContentViewController.h"
#import "HomePageDetailViewController.h"
#import "HomePageFeedbackView.h"
#import "HomePageFollowMoreView.h"
#import "HomePageContentViewCell.h"
#import "HomePageListHeadCell.h"
#import "HomePageListFootCell.h"
#import "HomePageListVideoCell.h"
#import "ReportViewController.h"
#import "RPAppShareView.h"
#import "UserInfoFollowModel.h"
#import "HomePageContentModel.h"
@interface HomePageContentViewController ()<HomePageListHeadCellDelegate,HomePageListFootCellDelegate,HomePageContentViewCellDelegate,HomePageListVideoCellDelegate>
@property (nonatomic,strong)NSURLSessionTask *task;
@end

@implementation HomePageContentViewController


-(NSInteger)numberOfItems{
    if (self.model != nil) {
        return 3;
    }
    return 0;
}

-(CGSize)sizeForItemAtIndex:(NSInteger)index{
    if (index == 0) {
        return CGSizeMake(kScreenW, 72);
    }else if (index == 1){
        return CGSizeMake(kScreenW, _model.cellHeight);
    }else{
        return CGSizeMake(kScreenW, _model.tag != nil?100:60);
    }
    
}

-(UICollectionViewCell *)cellForItemAtIndex:(NSInteger)index{
    if (index == 0) {
        HomePageListHeadCell *cell = [self.collectionContext dequeueReusableCellOfClass:[HomePageListHeadCell class] forSectionController:self atIndex:index];
        [cell bindViewModel:self.model];
        cell.delegate = self;
        return cell;
    }else if (index == 1) {
        // 视频
        if (self.model.contentType.intValue == 3) {
            HomePageListVideoCell *cell = [self.collectionContext dequeueReusableCellOfClass:[HomePageListVideoCell class] forSectionController:self atIndex:index];
            [cell bindViewModel:self.model];
            cell.delegate = self;
            return cell;
        }
        HomePageContentViewCell *cell = [self.collectionContext dequeueReusableCellOfClass:[HomePageContentViewCell class] forSectionController:self atIndex:index];
        [cell bindViewModel:self.model];
        cell.delegate = self;
        return cell;
    }else{
        HomePageListFootCell *cell = [self.collectionContext dequeueReusableCellOfClass:[HomePageListFootCell class] forSectionController:self atIndex:index];
        [cell bindViewModel:self.model];
        cell.delegate = self;
        return cell;
    }
  
}

- (void)didUpdateToObject:(id)object{
    _model = object;
}
- (void)didSelectItemAtIndex:(NSInteger)index{

    self.model.currentIndex = 0;
    
    if (index == 0) {
        if (self.model.contentType.intValue == 1 && self.showDetail) {
            [MobClick event:@"homePage_show_detail"];
            self.model.isShowAllContent = NO;
            self.showDetail(self.model,NO);
        }
    }
    
    if (index == 1) {
        if (self.showDetail) {
            [MobClick event:@"homePage_show_detail"];
            self.model.isShowAllContent = NO;
            self.showDetail(self.model,NO);
        }
    }
}


#pragma mark - HomePageListHeadCellDelegate
- (void)showUserInfo:(NSString *)userId{
    if (self.showUserInfo) {
        self.showUserInfo([NSNumber numberWithString:userId]);
    }
}
- (void)followUserInfo:(NSString *)userId{
    [self updateFollowStatus:YES];
    
}
- (void)showMoreViewWithCurrentModel:(HomePageItemModel *)currentModel{

    __weak typeof(self)weakSelf = self;
    if (currentModel.followType.intValue == 1 || currentModel.followType.intValue == 3) {
        HomePageFollowMoreView *moreView = [[HomePageFollowMoreView alloc]initWithCompleteBlock:^(NSInteger index) {
            if (index == 2) {
                if (![RPAppManager isLogin]) {
                    [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":weakSelf.viewController.navigationController} completion:nil];
                }else{
                    [MobClick event:@"homePage_report_click"];
                    ReportViewController *reportVC = [[ReportViewController alloc]initWithReportType:XHREPORTNORMAL reportId:currentModel.postId.stringValue];
                    [weakSelf.viewController.navigationController pushViewController:reportVC animated:YES];
                }
            }else{
                [weakSelf updateFollowStatus:NO];
            }
        }];
        [moreView show];
    }else{
        HomePageFeedbackView *feedbackView = [[HomePageFeedbackView alloc]initWithCompleteBlock:^{
            if (![RPAppManager isLogin]) {
                [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":weakSelf.viewController.navigationController} completion:nil];
            }else{
                [MobClick event:@"homePage_report_click"];
                ReportViewController *reportVC = [[ReportViewController alloc]initWithReportType:XHREPORTNORMAL reportId:currentModel.postId.stringValue];
                [weakSelf.viewController.navigationController pushViewController:reportVC animated:YES];
            }
        }];
        [feedbackView show];
    }
}
#pragma mark - HomePageContentViewCellDelegate
- (void)showAllContent{
    self.model.isShowAllContent = YES;
    if (self.showDetail) {
        self.showDetail(self.model,NO);
    }
}
- (void)showImageAtIndex:(NSInteger)index{
    self.model.currentIndex = index;
    if (self.showDetail) {
        self.showDetail(self.model,NO);
    }
}

#pragma mark - HomePageListVideoCellDelegate
- (void)videoAllContent{
    [self showAllContent];
}

#pragma mark - HomePageListFootCellDelegate
- (void)doDissOrLikeWithStatus:(BOOL)status{
    
    if (![RPAppManager isLogin]) {
        [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":self.viewController.navigationController} completion:nil];
        return;
    }
    
    [self.task cancel];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"type"] = status?@1:@2;
    param[@"postId"] = self.model.postId;
    
    if (status) {
        param[@"isTourist"] = self.model.isLike?@1:@2;
    }else{
        param[@"isTourist"] = self.model.isUnLike?@1:@2;
    }
    param[@"md5"] = [RPAppManager md5StrWithApi:DoDetailLike];
    self.task = [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(DoDetailLike) parames:param success:^(id responseObj) {
       
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateItemListSource" object:nil userInfo:@{@"data":self.model}];
    
    } failure:^(NSError *error) {
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
        if (status) {
            NSInteger likeNum = self.model.likeNum.intValue;
            if (self.model.isLike) {
                likeNum--;
            }else{
                likeNum++;
            }
            self.model.likeNum = @(likeNum);
            self.model.isLike = !self.model.isLike;
        }else{
            NSInteger unLikeNum = self.model.unlikeNum.intValue;
            if (self.model.isUnLike) {
                unLikeNum--;
            }else{
                unLikeNum++;
            }
            self.model.unlikeNum = @(unLikeNum);
            self.model.isUnLike = !self.model.isUnLike;
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateItemListSource" object:nil userInfo:@{@"data":self.model}];
        
    }];
}

- (void)shareWithCurrentModel:(HomePageItemModel *)itemModel{
    [self commonShareWithCurrentModel:itemModel];
}

- (void)commentWithCurrentModel:(HomePageItemModel *)itemModel{
    if (![RPAppManager isLogin]) {
        [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":self.viewController.navigationController} completion:nil];
        return;
    }
    
    if (self.showDetail) {
        self.showDetail(itemModel, YES);
    }
}

- (void)showTopicListViewWithTagModel:(HomeTagItemModel *)tagModel{
    if (self.showTopicList) {
        self.showTopicList(tagModel);
    }
}

#pragma mark - 更新follow状态
- (void)updateFollowStatus:(BOOL)status{
//
    if (![RPAppManager isLogin]) {
        [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":self.viewController.navigationController} completion:nil];
        return;
    }
    if (!status) {
        [MobClick event:@"homePage_follow_cancel"];
    }
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"followId"] = self.model.userId;
    param[@"type"] = status?@(1):@(2);
    param[@"md5"] = [RPAppManager md5StrWithApi:FollowAndUnFollow];
    [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(FollowAndUnFollow) parames:param success:^(id responseObj) {
        if (status) {
            [WHToast showMessage:@"关注成功" duration:2 finishHandler:nil];
        }else{
            [WHToast showMessage:@"取消关注" duration:2 finishHandler:nil];
        }
        NSNumber *followType =  responseObj[RESPONSE][@"followCode"];
        self.model.followType = followType;
    
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateItemListSource" object:nil userInfo:@{@"data":self.model}];
        
        __block BOOL isLocal = NO;

        RLMRealm *realm = [RLMRealm defaultRealm];
        [realm transactionWithBlock:^{
            RLMResults<UserInfoFollowModel *> *result = [UserInfoFollowModel allObjects];
            if (result.count > 0) {
                for (int index = 0; index < result.count; index++) {
                    UserInfoFollowModel *itemModel = result[index];
                    if (itemModel.userId == self.model.userId.longValue) {
                        itemModel.followCode = followType.longValue;
                        isLocal = YES;
                        break;
                    }
                }
            }
            if (!isLocal) {
                UserInfoFollowModel *userInfo = [[UserInfoFollowModel alloc]init];
                userInfo.userId = self.model.userId.longValue;
                userInfo.followCode = self.model.followType.longValue;
                userInfo.realName = self.model.realName;
                [realm addOrUpdateObject:userInfo];
            }
        }];
        
        //隐藏按钮
    } failure:^(NSError *error) {
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}

- (void)updateShareCountSource{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"postId"] = self.model.postId;
    param[@"md5"] = [RPAppManager md5StrWithApi:UpdatePostShareNum];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(UpdatePostShareNum) parames:param success:^(id responseObj) {
         
        int shareNum = self.model.shareNum.intValue;
        shareNum++;
        self.model.shareNum = @(shareNum);
  
        [MobClick event:@"home_page_share"];
        
        [MobClick event:@"dynamic_share_total" attributes:@{@"page":@"home"}];
        

        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateItemListSource" object:nil userInfo:@{@"data":self.model}];
        
    } failure:^(id error) {
            
    }];
}

#pragma mark - 分享统一方法
- (void)commonShareWithCurrentModel:(HomePageItemModel *)itemModel{
    
    
    
    [RPAppShareView showCompleteblock:^(XHShareViewPlatformType platformType) {
        UMSocialPlatformType type = UMSocialPlatformType_UnKnown;
        switch (platformType) {
            case XHShareViewPlatformTypeWeChatSession:
                type = UMSocialPlatformType_WechatSession;
                break;
            case XHShareViewPlatformTypeWeChatMoments:
                type = UMSocialPlatformType_WechatTimeLine;
                break;
            case XHShareViewPlatformTypeQQ:
                type = UMSocialPlatformType_QQ;
                break;
                
            case XHShareViewPlatformTypeQQZone:
                type = UMSocialPlatformType_Qzone;
                break;
            
            case XHShareViewPlatformTypeQQWeibo:
                type = UMSocialPlatformType_Sina;
                break;
            default:
                break;
        }
        
        if (![[UMSocialManager defaultManager] isInstall:type]) {
            if (type == UMSocialPlatformType_WechatSession || type == UMSocialPlatformType_WechatTimeLine) {
                [WHToast showMessage:@"请先安装微信" duration:2 finishHandler:nil];
            }
            if (type == UMSocialPlatformType_QQ || type == UMSocialPlatformType_Qzone) {
                [WHToast showMessage:@"请先安装QQ" duration:2 finishHandler:nil];
            }
            if (type == UMSocialPlatformType_Sina) {
                [WHToast showMessage:@"请先安装微博" duration:2 finishHandler:nil];
            }
            return;
        }
    
        
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];

        NSString *title = itemModel.contentText.length == 0?@"DDup":itemModel.contentText;
        
        
        NSDictionary *infoPlist = [[NSBundle mainBundle] infoDictionary];

        NSString *icon = [[infoPlist valueForKeyPath:@"CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconFiles"] lastObject];

        UIImage *shareImage= [UIImage imageNamed:icon];
        
        NSString* thumbURL =  @"";
        // 文字
        if (itemModel.contentType.intValue == 1) {
            
        // 图片
        }else if(itemModel.contentType.intValue == 2){
            thumbURL = itemModel.urls.firstObject;
        // 视频
        }else{
            __block HomePageContentModel *imageModel = nil;
            [itemModel.contents enumerateObjectsUsingBlock:^(HomePageContentModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (obj.seq.intValue == 1) {
                    imageModel = obj;
                    *stop = YES;
                }
            }];
            thumbURL = imageModel.postUrl;
            
        }
        //创建网页内容对象
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:title descr:@"分享我的Chinese高考" thumImage:itemModel.contentType.intValue == 1?shareImage:thumbURL];
        //设置网页地址
        shareObject.webpageUrl = [NSString stringWithFormat:@"%@dynamic?postId=%@",HtmlUrl,itemModel.postId];
        //分享消息对象设置分享内容对象
        messageObject.shareObject = shareObject;
        //调用分享接口
        [[UMSocialManager defaultManager] shareToPlatform:type messageObject:messageObject currentViewController:nil completion:^(id data, NSError *error) {
            if (error) {
                UMSocialLogInfo(@"************Share fail with error %@*********",error);
            }else{
              
            }
        }];
        
        [self updateShareCountSource];
    }];
}


@end
